package com.lagou.dw.hive.udf;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.junit.Test;

import java.util.ArrayList;

public class ParseJsonArray extends UDF {
    public ArrayList<String> evaluate(String jsonStr, String key){
        // 若传入空字符串，返回null
        if(Strings.isNullOrEmpty(jsonStr)){
            return null;
        }
        try{
            // 获取JSON Array
            JSONObject jsonObject = JSON.parseObject(jsonStr);
            JSONArray jsonArray = jsonObject.getJSONArray(key);
            ArrayList<String> lst = new ArrayList<>();
            for(Object o: jsonArray){
                lst.add(o.toString());
            }
            return lst;
        } catch(JSONException e){
            return null;
        }
    }

    @Test
    public void test1(){
        String str = "{\"id\": 1,\"ids\": [101,102,103],\"total_number\":3}";
        String key = "ids";
        ArrayList<String> evaluate = evaluate(str, key);
        System.out.println(JSON.toJSONString(evaluate));
}
}
